package com.google.code.swingonfire.component.foldable;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager2;
import java.awt.Rectangle;

public class FoldableLayout implements LayoutManager2
{
    private Component component = null;

    public FoldableLayout()
    {
        super();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void addLayoutComponent(Component component, Object constraints)
    {
        if (this.component != null)
        {
            throw new IllegalArgumentException("Only one component supported");
        }

        this.component = component;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void addLayoutComponent(String name, Component component)
    {
        addLayoutComponent(component, null);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void removeLayoutComponent(Component component)
    {
        if (this.component == component)
        {
            this.component = null;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public float getLayoutAlignmentX(Container target)
    {
        return 0.0f;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public float getLayoutAlignmentY(Container target)
    {
        return 0.0f;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void invalidateLayout(Container target)
    {
        // intentionally left blank
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Dimension preferredLayoutSize(Container parent)
    {
        return component.getPreferredSize();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Dimension minimumLayoutSize(Container parent)
    {
        return component.getMinimumSize();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Dimension maximumLayoutSize(Container parent)
    {
        return component.getMaximumSize();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void layoutContainer(Container parent)
    {
        if (component == null)
        {
            return;
        }

        JFoldableComponent foldableComponent = (JFoldableComponent) parent;
        Dimension size = (Dimension) foldableComponent.getSize().clone();

        if (foldableComponent.isFoldingHorizontal())
        {
            size.width = foldableComponent.getExpandedSize();
        }
        else
        {
            size.height = foldableComponent.getExpandedSize();
        }

        Rectangle bounds = new Rectangle(0, 0, size.width, size.height);
        component.setBounds(bounds);
    }
}
